﻿
using AppSocketService; 
using BCGPSCommon;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace BCGPSRESTful
{
    /// <summary>
    /// 注入服务
    /// </summary>
    public static class InjectionService
    {
        /// <summary>
        /// 不太懂
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddService(this IServiceCollection services)
        { 
            services.AddScoped<IPrincipalAccessor, PrincipalAccessor>();
            services.AddScoped<IClaimsAccessor, ClaimsAccessor>();
            services.AddScoped<IRedisService, RedisService>();
            InjectToServiceCollection(services, new AssemblyName("AppSocketService")); 

            return services;
        }

        private static void InjectToServiceCollection(IServiceCollection services, AssemblyName assemblyName)
        {
            Type[] types = Assembly.Load(assemblyName).GetTypes();
            var list = types.Where(s => s.GetTypeInfo().IsInterface);
            foreach (var item in list)
            {
                if (item.GetTypeInfo().GetCustomAttribute<NonInjectionAttribute>() != null)
                {
                    continue;
                }

                try
                {
                    Type implementClass = types.Single(s => s.GetTypeInfo().ImplementedInterfaces.Contains(item));
                    services.Add(new ServiceDescriptor(serviceType: item, implementationType: implementClass, lifetime: ServiceLifetime.Scoped));
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
